package inits

import (
	"fmt"
	"patient-srv/basic/config"
	"patient-srv/handler/model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// InitMySQL 初始化MySQL连接
func InitMySQL() {
	cfg := config.GlobalConfig.MySQL
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.User,
		cfg.Password,
		cfg.Host,
		cfg.Port,
		cfg.DBName,
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接数据库失败: " + err.Error())
	}

	config.GlobalDB = db

	// 自动迁移表结构
	if err = db.AutoMigrate(
		&model.User{},
		&model.Patient{},
		&model.Address{},
		&model.Order{},
		&model.Doctor{},
		&model.Consultation{},
	); err != nil {
		panic("数据库表迁移失败: " + err.Error())
	}

	fmt.Println("数据库连接成功")
}
